<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #container>div {
      width: 100%;
      height: 100px;
      background: yellowgreen;
      margin-bottom: 20px;
      text-align: center;
      line-height: 100px;
      font-size: 40px;
    }

    #container #top {
      height: 0;
    }

    #to-top {
      width: 100px;
      height: 40px;
      line-height: 40px;
      font-size: 13px;
      position: fixed;
      right: 20px;
      bottom: 20px;
      background-color: blueviolet;
      text-align: center;
      border-radius: 4px;
      cursor: pointer;
    }

    #container .div-sticky {
      position: sticky;
      top: 0;
      background-color: rgb(226, 205, 17);
    }
  </style>
</head>

<body>
  <main id="container">
    <div id="top"></div>
  </main>

  <div id="to-top">
    回到顶部
  </div>

  <script>
    // position:sticky是css定位新增属性
    const container = document.getElementById('container')

    function createDiv (i) {
      const div = document.createElement('div')
      div.textContent = i
      if (i == 5) {
        div.className = "div-sticky"
      }
      container.append(div)
    }

    for (let i = 0; i < 100; i++) {
      createDiv(i)
    }

    // 回到顶部
    const toTop = document.getElementById('to-top')
    toTop.addEventListener('click', () => {
      document.getElementById('top').scrollIntoView({ behavior: 'smooth' })
    }, false)
  </script>
</body>

</html>
